﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace SR.ExpressionEvaluator.Lib.Core
{
    internal class Evaluator : IEvaluator
    {
        private bool isValid = true;

        public event ExpressionPartFoundHandler ExpressionPartFound;

        public Dictionary<string, object> Variables { get; set; }

        public Evaluator()
        {
            Variables = new Dictionary<string, object>();

            Variables.Add("PI", Math.PI);
        }

        public T Evaluate<T>(string expression)
        {
            return (T)Convert.ChangeType(run(expression, false), typeof(T), null);
        }

        public bool Validate(string expression)
        {
            try
            {
                this.ExpressionPartFound += new ExpressionPartFoundHandler((epart, type) =>
                {
                    this.isValid = false;
                });
                run(expression, true);
                return this.isValid;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public Dictionary<string, string> GetProbables(string str)
        {
            if (String.IsNullOrEmpty(str))
            {
                return null;
            }

            Dictionary<string, string> probales = new Dictionary<string, string>();

            var q = (from t in Assembly.GetExecutingAssembly().GetTypes()
                     where t.IsClass
                        && t.Namespace == "SR.ExpressionEvaluator.Lib.Core.Functions"
                        && t.GetInterfaces().Contains(typeof(IFunction))
                     select t);

            foreach (Type type in q)
            {
                if (type.Name.ToUpper().StartsWith(str.ToUpper()))
                {
                    IFunction function = Activator.CreateInstance(type) as IFunction;
                    probales.Add(type.Name.ToUpper(), function.GetDefinition());
                }
            }

            foreach (KeyValuePair<string, object> vars in this.Variables)
            {
                if (vars.Key.ToUpper().StartsWith(str.ToUpper()))
                {
                    probales.Add(vars.Key, "Variable");
                }
            }

            return probales;
        }

        private object run(string expression, bool isValidating)
        {
            string buffer = string.Empty;
            bool isString = false;
            Stack<object> parts = new Stack<object>();

            //expression = expression.Replace(" ", "");
            if (expression.StartsWith("="))
            {
                expression = expression.Substring(1, expression.Length - 1);
            }

            foreach (char c in expression)
            {
                if (c == '\"' || c == '\'')
                {
                    isString = !isString;
                    buffer += c;
                    this.ExpressionPartFound(c.ToString(), ExpressionTypes.String);
                    continue;
                }

                if (isString)
                {
                    this.ExpressionPartFound(c.ToString(), ExpressionTypes.String);
                    buffer += c;
                }
                else
                {
                    switch (c)
                    {
                        case '(':
                            if (buffer != null)
                            {
                                try
                                {
                                    IFunction fTmp = Factory.GetFunction(buffer);
                                    raiseExpressionPartFound(buffer, ExpressionTypes.Function);
                                }
                                catch
                                {
                                    raiseExpressionPartFound(buffer, ExpressionTypes.Error);
                                }
                            }
                            raiseExpressionPartFound(c.ToString(), ExpressionTypes.Operand);
                            parts.Push(buffer + c);
                            buffer = string.Empty;
                            break;

                        case '+':
                        case '-':
                        case '*':
                        case '/':
                        case '^':
                        case '>':
                        case '<':
                        case ',':
                            if (!string.IsNullOrEmpty(buffer))
                            {
                                raiseExpressionPartFound(buffer, ExpressionTypes.Literal);
                                parts.Push(buffer);
                                buffer = string.Empty;
                            }
                            raiseExpressionPartFound(c.ToString(), ExpressionTypes.Operand);
                            parts.Push(c.ToString());
                            break;

                        case '=':
                            if (!string.IsNullOrEmpty(buffer))
                            {
                                raiseExpressionPartFound(buffer, ExpressionTypes.Literal);
                                parts.Push(buffer);
                                buffer = string.Empty;
                            };
                            string prevOperator = parts.Peek().ToString();
                            if (prevOperator == "<" || prevOperator == ">")
                            {
                                parts.Push(parts.Pop() + c.ToString());
                            }
                            else
                            {
                                parts.Push(c.ToString());
                            }
                            raiseExpressionPartFound(c.ToString(), ExpressionTypes.Operand);
                            break;

                        case ')':
                            if (!string.IsNullOrEmpty(buffer))
                            {
                                raiseExpressionPartFound(buffer, ExpressionTypes.Literal);
                                parts.Push(buffer);
                                buffer = string.Empty;
                            }
                            raiseExpressionPartFound(c.ToString(), ExpressionTypes.Operand);
                            List<object> curExpression = new List<object>();
                            while (parts.Count > 0 && !isValidating)
                            {
                                object part = parts.Pop();
                                if (part.ToString() == "(")
                                {
                                    curExpression.Reverse();
                                    parts.Push(evaluateOperators(curExpression).ToString());
                                    break;
                                }
                                else if (Regex.IsMatch(part.ToString(), @"^[A-Z0-9_]*\($"))
                                {
                                    IFunction func = Factory.GetFunction(part.ToString().Replace("(", ""));

                                    curExpression.Reverse();
                                    List<object> subExpression = new List<object>();
                                    foreach (object expr in curExpression)
                                    {
                                        if (expr.ToString() != ",")
                                        {
                                            subExpression.Add(expr);
                                        }
                                        else
                                        {
                                            func.Args.Add(evaluateOperators(subExpression));
                                            subExpression.Clear();
                                        }
                                    }
                                    func.Args.Add(evaluateOperators(subExpression));
                                    parts.Push(func.Evaluate());
                                    break;

                                    //string argsStr = String.Join("", curExpression);
                                    //List<string> args = argsStr.Split(new char[] { ',' }).ToList();
                                    //while (args.Remove(string.Empty)) ;

                                    //foreach (string arg in args)
                                    //{
                                    //    func.Args.Add(Evaluate<object>(arg));
                                    //}
                                    //parts.Push(func.Evaluate());
                                    //break;
                                }
                                else
                                {
                                    curExpression.Add(part);
                                }
                            }
                            break;

                        default:
                            buffer += c;
                            break;
                    }
                }
            }

            raiseExpressionPartFound(buffer, ExpressionTypes.Literal);
            parts.Push(buffer);

            if (isValidating)
            {
                return null;
            }

            List<object> finalExpression = new List<object>();
            while (parts.Count > 0)
            {
                finalExpression.Add(parts.Pop());
            }
            while (finalExpression.Remove(string.Empty)) ;

            return evaluateOperators(finalExpression);
        }

        private object evaluateOperators(List<object> parts)
        {
            object val = 0;
            int prevCount = parts.Count + 1;
            while(parts.Remove(string.Empty));

            while (parts.Count > 1 && parts.Count < prevCount)
            {
                prevCount = parts.Count;
                int opIndex = -1;

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "^"));
                if (opIndex != -1)
                {
                    val = Math.Pow(Convert.ToDouble(getLiteral(parts[opIndex - 1])),
                            Convert.ToDouble(getLiteral(parts[opIndex + 1])));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "/"));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) /
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "*"));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) *
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "+"));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) +
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "-"));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) -
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "="));
                if (opIndex != -1)
                {
                    val = Convert.ToBoolean(getLiteral(parts[opIndex - 1])) ==
                            Convert.ToBoolean(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == ">"));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) >
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "<"));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) <
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == ">="));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) >=
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }

                opIndex = parts.IndexOf(parts.FirstOrDefault(p => p.ToString() == "<="));
                if (opIndex != -1)
                {
                    val = Convert.ToDouble(getLiteral(parts[opIndex - 1])) <=
                            Convert.ToDouble(getLiteral(parts[opIndex + 1]));

                    parts[opIndex] = val;
                    parts.RemoveAt(opIndex + 1);
                    parts.RemoveAt(opIndex - 1);
                    continue;
                }
            }

            if (parts.Count == 1)
            {
                return getLiteral(parts[0]);
            }

            return val;
        }

        private object getLiteral(object ex)
        {
            if (this.Variables.ContainsKey(ex.ToString()))
            {
                return Variables[ex.ToString()];
            }
            else if (ex.ToString().StartsWith("\"") && ex.ToString().EndsWith("\""))
            {
                return ex.ToString().Substring(1, ex.ToString().Length - 2);
            }
            else if (ex.ToString().StartsWith("'") && ex.ToString().EndsWith("'"))
            {
                return ex.ToString().Remove(ex.ToString().Length - 1).Remove(0);
            }
            else if (ex.ToString().ToUpper() == "TRUE")
            {
                return true.ToString();
            }
            else if (ex.ToString().ToUpper() == "FALSE")
            {
                return false.ToString();
            }
            return ex;
        }

        private void raiseExpressionPartFound(string expressionPart, ExpressionTypes type)
        {
            if (this.ExpressionPartFound != null)
            {
                if (this.Variables.ContainsKey(expressionPart))
                {
                    this.ExpressionPartFound(expressionPart, ExpressionTypes.Variable);
                }
                else if (type == ExpressionTypes.Literal && expressionPart.StartsWith("\""))
                {
                    //this.ExpressionPartFound(expressionPart, ExpressionTypes.String);
                }
                else if (type == ExpressionTypes.Literal && expressionPart.StartsWith("'"))
                {
                    //this.ExpressionPartFound(expressionPart, ExpressionTypes.String);
                }
                else if (expressionPart.ToUpper() == "TRUE")
                {
                    this.ExpressionPartFound(expressionPart, ExpressionTypes.Boolean);
                }
                else if (expressionPart.ToUpper() == "FALSE")
                {
                    this.ExpressionPartFound(expressionPart, ExpressionTypes.Boolean);
                }
                else
                {
                    this.ExpressionPartFound(expressionPart, type);
                }
            }
        }
    }
}
